<?php
define('FENGTOPsso_ROOT', dirname(__FILE__));
include_once 'config.php';
include_once 'database/dbmysql.php';
$mysqldb  =  new DB(DB_HOST, DB_USER, DB_PW, DB_NAME);

session_save_path(SESSION_PATH);
session_set_cookie_params(SESSION_TIME); 
session_name("FengTop");
session_start();

function getStartTime() {
	list ( $_SESSION['usec'], $_SESSION['sec'] ) = explode ( " ", microtime () );
}
	
function selectOnLine() {
	global $mysqldb;
	$selectOnlineSql = "SELECT count(*)
	                      FROM `".DB_TABLEPRE."onlineuser`
	                     WHERE `ticket` = '".$_SESSION['FOnlineUser']['ticket']."'";
	return $mysqldb->GetOne($selectOnlineSql);
}
	
function deleteOnLine() {
	global $mysqldb;
	$deleteOnlineSql = "DELETE FROM `".DB_TABLEPRE."onlineuser` WHERE `ticket` = '".$_SESSION['FOnlineUser']['ticket']."' or `username` = '{$_POST['userName']}'";
	$mysqldb->Query($deleteOnlineSql);
}
	
function insertOnLine() {
	global $mysqldb;
	getStartTime();
	
	//检查是否已登录
	if (selectOnLine()) {
		deleteOnLine();
	}
	
	$insertOnlineSql = "INSERT INTO `".DB_TABLEPRE."onlineuser` (
 							        `ticket` ,
								    `username` ,
								    `expiry` ,
								    `data` )
							VALUES (
 									'".$_SESSION['FOnlineUser']['ticket']."',
 									'".$_POST['userName']."',
 									'".$_SESSION['sec']."',
 									'".json_encode($_SESSION['FOnlineUser'])."'
									)";
//$_SESSION['insertOnlineSql'] = $insertOnlineSql;
	$mysqldb->Query($insertOnlineSql);
}

function setClientCookie($result) {
	global $mysqldb;
	
	require_once FENGTOPsso_ROOT.'/public/CookieHandle.class.php';
	$clientCookie = new CookieHandle(& $mysqldb);
	$clientCookie->setClientCookie($result);
}

header('Content-type: text/html; charset='.FTsso_CHARSET);

$selectSql = "SELECT * 
		    FROM `".DB_TABLEPRE."user_".substr(md5($_POST['userName']), 0, 2)."` 
		   WHERE `username`='{$_POST['userName']}'
		     AND `password` = '".md5($_POST['userPwd'])."'";
$result = $mysqldb->GetOne($selectSql);

if ($result != 0) {
	$result['sessionID'] = session_id();
	$result['ticket'] = md5($result['sessionID']);
	$_SESSION['FOnlineUser'] = $result;
	insertOnLine();
	setClientCookie($result);
}else {
	$result = array ('a'=>0);
}

echo json_encode($result);
//echo json_encode($GLOBALS);
?>